package wh.coach.pivot3.table.dynamic;

import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author xhw
 * @date 2024/3/18
 */

public class DataTableView {
    public static DataPivotTableView generatePivotTableView(DataGroups groups, List<Aggregation> aggregations) {
        DataPivotTableView dataPivotTableView = new DataPivotTableView();

        final ArrayList<GroupKey> groupKeys = new ArrayList<>(groups.getGroupKeys());

        //拿到groups里的rowsKeys数据并且去重
        List<List<String>> rowKeys = groupKeys.stream().map(GroupKey::getRowsKeys).distinct().toList();

        //拿到groups里的columnsKeys数据并且去重
        List<List<String>> columnKeys = groupKeys.stream().map(GroupKey::getColumnsKeys).distinct().toList();

        //创建表头
        int columnSize = rowKeys.size() + columnKeys.size() * aggregations.size();
        List<String> header = Lists.newArrayListWithCapacity(columnSize);
        header.addAll(groups.getRowsKeys());

        //设置表头，将去重之后的columnKeys和要聚合的类型进行拼接
        for (List<String> columnKey : columnKeys) {
            for (Aggregation aggregation : aggregations) {
                header.add(columnKey + aggregation.getTitle());
            }
        }

        //设置表头
        dataPivotTableView.setHeader(header);
        //rowKeys就是行数据，有多少个分组就有多少行
        for (List<String> rowkey : rowKeys) {
            //拼接一个结果
            List<String> row = Lists.newArrayListWithExpectedSize(columnSize);
            row.addAll(rowkey);

            for (List<String> columnKey : columnKeys) {
                //构建一个新的key之后拿这个key去取到成绩
                GroupKey key = new GroupKey(rowkey, columnKey);
                for (Aggregation aggregation : aggregations) {
                    Number value = groups.calculate(aggregation, key);
                    row.add(Optional.ofNullable(value).orElse(0).toString());

                }
            }

            //添加结果
            dataPivotTableView.addRow(row);
        }
        return dataPivotTableView;
    }
}
